package com.android.wuziqi;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.android.jay.music.R;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

/**
 * Created by wzp on 2020/3/3 0003.
 * <p>
 * 描述  ：todo
 */
public class WuziqiTabel extends View {

    private int mPanelWidth;
    //绘制尺寸尽量用float
    private float mLineHeight;

    private int MAX_LINE = 10;

    private Paint mPaint;

    private Bitmap mWhitePiece;
    private Bitmap mBlackPiece;

    private float ratioPieceOfLineHeight = 3 * 1.0f / 4;

    //用户点击的坐标
    private ArrayList<Point> mWhiteArray = new ArrayList<>();
    private ArrayList<Point> mBlackArray = new ArrayList<>();
    //先手
    private boolean mIsWhite = true;
    private boolean mIsGameOver;
    private boolean mIsWhiteWinner;

    private int MAX_IN_LINE = 5;

    public WuziqiTabel(Context context) {
        this(context, null);
    }

    public WuziqiTabel(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WuziqiTabel(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setBackgroundColor(0x44ff0000);
        init();


    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(0x88000000);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mWhitePiece = BitmapFactory.decodeResource(getResources(), R.mipmap.stone_w2);
        mBlackPiece = BitmapFactory.decodeResource(getResources(), R.mipmap.stone_b1);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width = Math.min(widthSize, heightSize);
        /**
         *
         * 1、MeasureSpec.UNSPECIFIED -> 未指定尺寸
         *
         * 2、MeasureSpec.EXACTLA -> 精确尺寸，控件的宽高指定大小或者为FILL_PARENT
         *
         * 3、MeasureSpec.AT_MOST -> 最大尺寸，控件的宽高为WRAP_CONTENT，
         *   控件大小一般随着控件的子空间或内容进行变化，此时控件尺寸只要不超过父控件允许的最大尺寸
         *
         * **/
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            width = heightSize;
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            width = widthSize;
        }
        setMeasuredDimension(width, width);

    }

    /**
     * 在尺寸确定发生变化的时候
     **/
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mPanelWidth = w;
        mLineHeight = mPanelWidth * 1.0f / MAX_LINE;
        int piece = (int) ((mLineHeight * ratioPieceOfLineHeight));
        mWhitePiece = Bitmap.createScaledBitmap(mWhitePiece, piece, piece, false);
        mBlackPiece = Bitmap.createScaledBitmap(mBlackPiece, piece, piece, false);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPiece(canvas);
        checkGameOver();
    }

    private void checkGameOver() {
        boolean whitewin = checkFiveInLine(mWhiteArray);
        boolean blackwin = checkFiveInLine(mBlackArray);
        if (whitewin || blackwin) {
            mIsGameOver = true;
            if (whitewin) mIsWhiteWinner = true;
            else mIsWhiteWinner = false;
            if (mLisenter != null)
                mLisenter.onWinnerLisenter(mIsWhiteWinner);
        }
    }

    private boolean checkFiveInLine(List<Point> array) {
        for (Point point : array) {
            int x = point.x;
            int y = point.y;
            boolean win = checkHorizontal(x, y, array);
            if (win) return true;
            win = checkVertical(x, y, array);
            if (win) return true;
            win = checkLeftDiagonl(x, y, array);
            if (win) return true;
            win = checkRightDiagonl(x, y, array);
            if (win) return true;
        }
        return false;
    }

    /**
     * 判断横向胜利
     **/
    private boolean checkHorizontal(int x, int y, List<Point> array) {

        int count = 1;
        for (int i = 1; i < MAX_IN_LINE; i++) {
            if (array.contains(new Point(x - i, y))) {
                count++;
            } else {
                break;
            }

        }
        if (count == MAX_IN_LINE) {
            return true;
        }
        for (int i = 1; i < MAX_IN_LINE; i++) {
            if (array.contains(new Point(x + i, y))) {
                count++;
            } else {
                break;
            }

        }

        if (count == MAX_IN_LINE) {
            return true;
        }
        return false;
    }


    /**
     * 判断纵向胜利
     **/
    private boolean checkVertical(int x, int y, List<Point> array) {

        int count = 1;
        for (int i = 1; i < MAX_IN_LINE; i++) {
            if (array.contains(new Point(x, y + i))) {
                count++;
            } else {
                break;
            }

        }
        if (count == MAX_IN_LINE) {
            return true;
        }
        for (int i = 1; i < MAX_IN_LINE; i++) {
            if (array.contains(new Point(x, y - i))) {
                count++;
            } else {
                break;
            }

        }

        if (count == MAX_IN_LINE) {
            return true;
        }
        return false;
    }


    /**
     * 左斜胜利
     **/
    private boolean checkLeftDiagonl(int x, int y, List<Point> array) {

        int count = 1;
        for (int i = 1; i < MAX_IN_LINE; i++) {
            if (array.contains(new Point(x + i, y + i))) {
                count++;
            } else {
                break;
            }

        }
        if (count == MAX_IN_LINE) {
            return true;
        }
        for (int i = 1; i < MAX_IN_LINE; i++) {
            if (array.contains(new Point(x - i, y - i))) {
                count++;
            } else {
                break;
            }

        }

        if (count == MAX_IN_LINE) {
            return true;
        }
        return false;
    }


    /**
     * 右斜胜利
     **/
    private boolean checkRightDiagonl(int x, int y, List<Point> array) {

        int count = 1;
        for (int i = 1; i < MAX_IN_LINE; i++) {
            if (array.contains(new Point(x - i, y + i))) {
                count++;
            } else {
                break;
            }

        }
        if (count == MAX_IN_LINE) {
            return true;
        }
        for (int i = 1; i < MAX_IN_LINE; i++) {
            if (array.contains(new Point(x + i, y - i))) {
                count++;
            } else {
                break;
            }

        }

        if (count == MAX_IN_LINE) {
            return true;
        }
        return false;
    }

    private void drawPiece(Canvas canvas) {
        for (int i = 0; i < mWhiteArray.size(); i++) {
            Point whitePoint = mWhiteArray.get(i);
            canvas.drawBitmap(mWhitePiece, (whitePoint.x + (1 - ratioPieceOfLineHeight) / 2) * mLineHeight
                    , (whitePoint.y + (1 - ratioPieceOfLineHeight) / 2) * mLineHeight, null);
        }

        for (int i = 0; i < mBlackArray.size(); i++) {
            Point blackPoint = mBlackArray.get(i);
            canvas.drawBitmap(mBlackPiece, (blackPoint.x + (1 - ratioPieceOfLineHeight) / 2) * mLineHeight
                    , (blackPoint.y + (1 - ratioPieceOfLineHeight) / 2) * mLineHeight, null);
        }
    }

    private void drawBoard(Canvas canvas) {
        int w = mPanelWidth;
        float lineHeight = mLineHeight;
        for (int i = 0; i < MAX_LINE; i++) {
            int startX = (int) (lineHeight / 2);
            int endX = (int) (w - lineHeight / 2);
            int startY = (int) ((0.5 + i) * lineHeight);
            canvas.drawLine(startX, startY, endX, startY, mPaint);

            canvas.drawLine(startY, startX, startY, endX, mPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mIsGameOver) {
            return false;
        }
        int action = event.getAction();
        if (action == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            Point point = getVailPoint(x, y);
            if (mWhiteArray.contains(point) || mBlackArray.contains(point)) {
                return false;
            }
            if (mIsWhite) {
                mWhiteArray.add(point);
            } else {
                mBlackArray.add(point);
            }
            invalidate();
            mIsWhite = !mIsWhite;
            //返回true 是告诉父类 这个事件交给子类处理
            return true;
        }


        return true;
    }

    private Point getVailPoint(int x, int y) {
        int vailX = (int) (x / mLineHeight);
        int vailY = (int) (y / mLineHeight);
        Point point = new Point(vailX, vailY);
        return point;

    }

    private winnerLisenter mLisenter;

    public void setWinnerLisenter(winnerLisenter lisenter) {
        this.mLisenter = lisenter;
    }

    public interface winnerLisenter {
        void onWinnerLisenter(boolean whitewin);
    }


    private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_black_array";

    @Nullable
    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE, super.onSaveInstanceState());
        bundle.putBoolean(INSTANCE_GAME_OVER, mIsGameOver);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY, mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY, mBlackArray);
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            mIsGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            mWhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mBlackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }
        super.onRestoreInstanceState(state);

    }

    public void star() {
        mIsGameOver = false;
        mWhiteArray.clear();
        mBlackArray.clear();
        mIsWhiteWinner = false;
        invalidate();
    }
}
